package com.budwk.app.sqfwV2.generator.dayingRoadExcel;

import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.component.DictComponent;
import com.budwk.app.sqfw.component.CommonComponent;
import com.budwk.app.sqfw.constants.DictConstants;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfwDoc.bo.SqfwExcelForSummaryBO;
import com.budwk.app.sqfwDoc.bo.SqfwExcelJudgeRes;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.BaseExcelParamDTO;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.BaseTemplateExcelGenerator;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.SqfwExcelCreateCommonBO;
import com.budwk.app.sqfwV2.component.DayingRoadPdfComponent;
import com.budwk.app.sqfwV2.dto.dto.FireSafetyOnDayingRoadPdfDTO;
import com.budwk.app.sqfwV2.dto.dto.centuryCity.SafeCheckTaskParamDataDTO;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.SandwichingVo;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.template.CateringIndustryExcelVo;
import com.budwk.app.sqfwV2.dto.image.FireSafetyOnDayingRoadExcelImageConfigBO;
import com.budwk.app.sqfwV2.enums.DayingRoadFileServiceEnum;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.StrUtil;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.budwk.app.util.poiUtils.excelPictureConfigBO.ExcelFileCreateParamBO;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 7 燃气、燃料排查情况汇总/Excel
 */

@Slf4j
public class CateringIndustryGenerator extends BaseTemplateExcelGenerator implements DayingRoadExcelGenerator {

    @Override
    protected String getTemplateName() {
        return DayingRoadFileServiceEnum.DAYING_ROAD_EXCEL_FUAL.getFilePath();
    }

    /**
    * 可以参照 {@link com.budwk.app.sqfw.enums.DownLoadFileNameEnum}
    *
    * @return 文件名名称
    */
    @Override
    public String getDownloadFileName() {
        //TODO 在这里返回你生成的文件名名称，注意注意注意不用带上后缀
        return DayingRoadPdfComponent.getDictName(DayingRoadFileServiceEnum.DAYING_ROAD_EXCEL_FUAL.getCode(), null);
    }

    /**
     * 用户自定义excel基础参数，比如表头这样的公用数据
     * @param excelParam 已经填充的基础数据据
     * @param excelCreateParam excel生成提供的原料
     */
    @Override
    protected void customerPopularSheetBaseParam(Map<String, Object> excelParam, SqfwExcelCreateCommonBO excelCreateParam) {
        log.info("CateringIndustryGenerator build param: {}", excelParam);
        BaseExcelParamDTO baseExcelParamDTO = excelCreateParam.getBaseExcelParamDTO();
        String createUserId = baseExcelParamDTO.getCreateUserId();
        SysUserService userService = NutzIocUtils.getBean(SysUserService.class);
        Sys_user user = userService.fetch(createUserId);
        excelParam.put("fillUserNamePhone", baseExcelParamDTO.getCreateUserName() + "-" + user.getMobile());
        excelParam.put("unitName", DayingRoadPdfComponent.getUnitName(baseExcelParamDTO));
        excelParam.put("district", DayingRoadPdfComponent.getDistrict(baseExcelParamDTO.getDistrict()));
    }

    @Override
    protected void customerPopularSheetDataParam(List<Map<String, Object>> listMap, SqfwExcelCreateCommonBO excelCreateParam) {
        List<Sqfw_formSummary_new> summaryList = DayingRoadPdfComponent.getSummaryList(listMap, excelCreateParam);
        int num = 1;
        for (Sqfw_formSummary_new summaryNew : summaryList) {
            String paramData = summaryNew.getParamData();
            FireSafetyOnDayingRoadPdfDTO roadPdfDTO = JSONObject.parseObject(paramData, FireSafetyOnDayingRoadPdfDTO.class);
            boolean isGenerateExcel = isGenerateExcel(roadPdfDTO);
            if (!isGenerateExcel) {
                continue;
            }
            // 获取数据
            Map<String, Object> map = buildCateringIndustryExcelVo(roadPdfDTO, summaryNew);
            // 转为map
            map.put("num", num ++);
            listMap.add(map);
        }
        log.info("build map end");
    }

    /**
     * 【用户用火用电情况】状态除了只有【无】或只有【用炭】的状态外，生成表格。
     * @param roadPdfDTO
     */
    public boolean isGenerateExcel(FireSafetyOnDayingRoadPdfDTO roadPdfDTO) {
        // 判断a5是否为重点场所 选择重点场所 不生成表格
        if (DayingRoadPdfComponent.isKeyLocations(roadPdfDTO)) {
            return false;
        }
        String fireAndElectricityUsage = roadPdfDTO.getFireAndElectricityUsage();
        if (StringUtils.isNotEmpty(fireAndElectricityUsage)) {
            if (fireAndElectricityUsage.equals(DictConstants.BOTTLED_ETHER_ELECTRICITY_NO)) {
                return false;
            }
            if (fireAndElectricityUsage.equals(DictConstants.BOTTLED_ETHER_CHARCOAL)) {
                return false;
            }
        }
        return true;
    }

    private CateringIndustryExcelVo buildBaseInfo(FireSafetyOnDayingRoadPdfDTO roadPdfDTO, Sqfw_formSummary_new sqfwFormSummaryNew) {
        CateringIndustryExcelVo excelVo = new CateringIndustryExcelVo();
        excelVo.setUnitNameStreet(StrUtil.replaceNullStr(sqfwFormSummaryNew.getCounty()) + "，" + sqfwFormSummaryNew.getCommunity())
                .setAddress(roadPdfDTO.getAddress())
                .setPlaceName(roadPdfDTO.getPlaceName())
                .setNameAndPhone(roadPdfDTO.getOperator() + " " + roadPdfDTO.getOperatorTelephone());
        return excelVo;
    }

    private void buildGas(FireSafetyOnDayingRoadPdfDTO roadPdfDTO, CateringIndustryExcelVo excelVo) {
        SafeCheckTaskParamDataDTO gam = roadPdfDTO.getGasAlarmsNumber();
        excelVo.setSetupNormal("否").setGasAlarmsNumber("0");
        if (gam != null) {
            excelVo.setSetupNormal("是").setGasAlarmsNumber(gam.getKey());
            if ("0".equals(gam.getKey())) {
                excelVo.setSetupNormal("否");
            }
        }
        SafeCheckTaskParamDataDTO isP = roadPdfDTO.getIsAlarmNormal();
        if (isP != null) {
            excelVo.setAlarmNormal("-");
            if (StringUtils.isNotEmpty(isP.getKey())) {
                if (isP.getKey().equals("true")) {
                    excelVo.setAlarmNormal("是");
                }
                if (isP.getKey().equals("false")) {
                    excelVo.setAlarmNormal("否");
                }
            }
        }
        String fireAndElectricityUsage = roadPdfDTO.getFireAndElectricityUsage();
        if (StringUtils.isNotEmpty(fireAndElectricityUsage)) {
            // 使用燃气属于（1、瓶装液化气、2、瓶装天然气、3、瓶装二甲醚、4、用电、5、管道燃气）
            List<String> list = DictComponent.listGas();
            List<String> indexList = new ArrayList<>();
            for (int j = 0; j < list.size(); j++) {
                if (fireAndElectricityUsage.contains(list.get(j))) {
                    indexList.add(String.valueOf(j +1));
                }
            }
            excelVo.setGasIndex(String.join(",", indexList));
        }
    }

    private void buildGasUgage(FireSafetyOnDayingRoadPdfDTO roadPdfDTO, CateringIndustryExcelVo excelVo) {
        // 使用燃料属于（例如：1、甲醇、2、乙醇、3、丙醇、4、丁烷、5、柴油、6、白油、7、黄油、8、植物油、9、环保油、10、用电、11、其他燃油等）
        String gasUgage = roadPdfDTO.getGasUgage();
        if (StringUtils.isNotEmpty(gasUgage)) {
            List<String> codeList = DictComponent.GAS_USAGE_LIST();
            List<String> indexList = new ArrayList<>();
            for (int i = 0; i < codeList.size(); i++) {
                if (gasUgage.contains(codeList.get(i))) {
                    indexList.add(String.valueOf(i +1));
                }
            }
            excelVo.setUserFuelIndex(String.join(",", indexList));
        }
        // 存储总量（日/升）
        excelVo.setGasStorageTotal(StrUtil.replaceNullStr(roadPdfDTO.getGasStorageTotal()));
        String dictName = DayingRoadPdfComponent.getDictName(roadPdfDTO.getAlcoholBasedFuelUse(), null);
        excelVo.setAlcoholBasedFuelUse(StrUtil.replaceNullStr(dictName));
    }

    private void buildNatureHouseUse(FireSafetyOnDayingRoadPdfDTO roadPdfDTO, CateringIndustryExcelVo excelVo) {
        String buildingType = roadPdfDTO.getBuildingType();
        if (StringUtils.isNotEmpty(buildingType)) {
            excelVo.setSelfBuiltHouses("否");
            SandwichingVo s = roadPdfDTO.getSandwichConstructionUse();
            if (DictConstants.BUILDING_TYPE_PURPOSES.equals(buildingType)) {
                excelVo.setSelfBuiltHouses("是");
            }
            String floorArea = String.format("%s%s%s", "0", "、", roadPdfDTO.getPlaceArea());
            if (s != null && StringUtils.isNotEmpty(s.getDjJcNum())) {
                floorArea = String.format("%s%s%s", s.getDjJcNum(), "、", roadPdfDTO.getPlaceArea());
            }
            excelVo.setFloorArea(floorArea);
        }
    }

    private Map<String, Object> buildCateringIndustryExcelVo(FireSafetyOnDayingRoadPdfDTO roadPdfDTO, Sqfw_formSummary_new sqfwFormSummaryNew) {
        // 1 基本信息
        CateringIndustryExcelVo excelVo = buildBaseInfo(roadPdfDTO, sqfwFormSummaryNew);
        // 2 燃气
        buildGas(roadPdfDTO, excelVo);
        // 3 新型燃料
        buildGasUgage(roadPdfDTO, excelVo);
        // 4 房屋使用性质
        buildNatureHouseUse(roadPdfDTO, excelVo);
        excelVo.setRiskControlMeasures(StrUtil.replaceNullStr(roadPdfDTO.getRiskControlMeasures()))
                .setRemark(StringUtils.EMPTY);
        Map<String, Object> map = CommonComponent.entityToMap(excelVo);
        // 购买渠道（销售企业）是否有相关证件
        map.put("purchasingChannelsPhoto", null);
        map.put("purchasingChannelsPhotoStr", "");
        if (StringUtils.isNotEmpty(roadPdfDTO.getPurchasingChannelsPhoto())) {
            map.put("purchasingChannelsPhoto", CommonFormOfficeUtils.addPictureToByteList(roadPdfDTO.getPurchasingChannelsPhoto(), 1));
        } else {
            map.put("purchasingChannelsPhotoStr", "-");
        }
        return map;
    }

    @Override
    protected void completeExcelFileCreateParam(ExcelFileCreateParamBO excelFileCreateParam) {

    }

    @Override
    protected void customerPopularRowDataMap(Map<String, Object> rowDataMap, SqfwExcelForSummaryBO forSummaryBO) {

    }

    /**
     * 如果在遍历之前就能够判断excel是否生成，那么就在这个方法中进行判断
     * @param excelCreateParam excel生成所需的最为全面的数据
     * @param excelParam excel已经填充的部分数据
     */
    @Override
    protected SqfwExcelJudgeRes judgeDataIntoExcelBeforeErgodic(SqfwExcelCreateCommonBO excelCreateParam, Map<String, Object> excelParam) {
        return DayingRoadPdfComponent.getSqfwExcelJudgeRes(excelCreateParam, new CateringIndustryGenerator());
    }

    /**
    * 如果在遍历之后能够判断excel是否生成，那么就在这个方法中进行判断
    * @param excelParam excel已经填充的部分数据
    */
    @Override
    protected SqfwExcelJudgeRes judgeDataIntoExcelBeforeCreate(Map<String, Object> excelParam) {
        return null;
    }

    @Override
    protected Class<?> getImageConfigBO() {
        return FireSafetyOnDayingRoadExcelImageConfigBO.class;
    }
}
